//
//  AudioAbstractViewController.m
//  TestAispeech
//
//  Created by shaowei on 13-9-8.
//  Copyright (c) 2013年 LianZhan. All rights reserved.
//

#import "AudioAbstractViewController.h"

@interface AudioAbstractViewController ()

@end

@implementation AudioAbstractViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化按钮状态
    [self setButtonState:ButtonStateOfStop];
    
    //初始化语音识别器
    self.recognizer = [[[AiRecognizerDialog alloc]init ] autorelease] ;
    [_recognizer setMAiRecognizerDelegate:self];
    [_recognizer setAiRecognizerDialogStyle:DIALOG_STYLE_DARK];
    
    AiEngineConfig *engineConfig = [[AiEngineConfig alloc] init];
    [engineConfig setAppKey:kAppKeyOfAISpeech];
    [engineConfig setAppSecretKey:kSecretKeyOfAISpeech];
    [_recognizer createAiRecognizerDialog:engineConfig] ;
    
    //设置语音识别器参数
    self.paramsOfRecognizer = [[[ASRParams alloc] init] autorelease];
    [_paramsOfRecognizer setReqRes:@"assist"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTextViewOfResult:nil];
    [self setButtonOfRecord:nil];
    [super viewDidUnload];
}

- (void)dealloc
{
    [_recognizer release];
    [_paramsOfRecognizer release];
    [_textViewOfResult release];
    [_buttonOfRecord release];
    [super dealloc];
}

#pragma mark - private

- (void)setButtonState:(ButtonState)buttonState{
    _buttonState = buttonState;
    
    switch (_buttonState) {
        case ButtonStateOfRecording:{
            [_buttonOfRecord setTitle:@"停止声音识别" forState:UIControlStateNormal];
        }
            break;
        case ButtonStateOfStop:{
            [_buttonOfRecord setTitle:@"开始声音识别" forState:UIControlStateNormal];
            _textViewOfResult.text = @"";//清空输出框
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - Function - Public

- (NSString *)getRecognizerStringFromString:(NSString *)subString{
    NSString *regularString = @"(?<=\"rec\":\")\\w+(?=\")";//使用正则取出返回值里面的识别语音
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularString
                                                                                       options:NSRegularExpressionCaseInsensitive
                                                                                         error:nil];
    NSTextCheckingResult *result = [regularExpression firstMatchInString:subString
                                                                 options:0
                                                                   range:NSMakeRange(0, subString.length)];
    if (result.range.length) {
        return [subString substringWithRange:result.range];
    }else{
        return nil;
    }
    
    
}


#pragma mark - AiRecognizerDelegate

/**
 *	@brief	引擎初始化是否成功
 *
 *	@param 	state      是否成功 (成功:OPT_SUCCESS 失败:OPT_FAILED)
 */
-(void)aiSpeechEngine:(AiSpeechEngine *)engine onInit:(NSNumber *)state {
    
    if(![state isEqualToNumber:[NSNumber numberWithInt:OPT_SUCCESS]]) {
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"引擎初始化失败"
                                                     message:nil
                                                    delegate:nil
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles: nil];
        [av show];
        [av release];
        
        self.buttonOfRecord.enabled = NO;
    }
}

/**
 *	@brief	引擎运行完成
 *
 *	@param 	engine      引擎对象
 *	@param 	stopType 	停止类型，参见 AISPEECHENGINE_STOPTYPE
 */
-(void)aiSpeechEngineDidFinishRecording:(AiSpeechEngine *)engine stopType:(int)stopType{
    [self setButtonState:ButtonStateOfStop];
}


/**
 *	@brief	引擎收到了评测结果
 *
 *	@param 	engine      引擎对象
 *	@param 	recordId 	录音流ID
 *	@param 	jsonString 	服务端返回JSON结果
 */
-(void)aiSpeechEngine:(AiSpeechEngine *)engine didReceive:(NSString *)recordId responseJson:(NSString *)jsonString{
    NSLog(@"receive-json:\n%@",jsonString) ;
    
    NSString *resultString = [self getRecognizerStringFromString:jsonString];
    if (resultString) {
        [self.textViewOfResult setText:resultString];
    }
}

/**
 *	@brief	上报录音数据
 *
 *	@param 	engine      引擎对象
 *	@param 	recordId 	录音ID
 *	@param 	binaryData 	音频数据
 */
-(void)aiSpeechEngine:(AiSpeechEngine *)engine didReceive:(NSString *)recordId responseBinary:(NSData *)binaryData{
    
}

/**
 *	@brief	引擎收到录音音量大小
 *
 *	@param 	engine      引擎对象
 *	@param 	recordId 	录音流ID
 *	@param 	volume      服务端返回音量大小
 */
-(void)aiSpeechEngine:(AiSpeechEngine *)engine didReceive:(NSString *)recordId volume:(NSNumber *)volume{
    
}


/**
 *	@brief	引擎收到了出错响应
 *
 *	@param 	engine      引擎对象
 *	@param 	recordId 	录音ID
 *	@param 	jsonString 	错误JSON字符串
 */
-(void)aiSpeechEngine:(AiSpeechEngine *)engine didReceive:(NSString *)recordId errorJson:(NSString *)jsonString{
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"error"
                                                 message:jsonString
                                                delegate:nil
                                       cancelButtonTitle:@"确定"
                                       otherButtonTitles: nil];
    [av show];
    [av release];
}

#pragma mark - action
- (IBAction)actionRecord:(id)sender {
    if (_buttonState == ButtonStateOfStop) {
        //弹出录音界面
        [_recognizer show:_paramsOfRecognizer] ;
    }
}



@end
